<script setup>
import { ref, onBeforeMount } from "vue";
import {
  getUserPostsService,
  getUserTopicsService,
  deleteUserPostService,
  deleteUserTopicService,
} from "@/api/info";
import { useAuthStore } from "@/stores";
import { ElMessage } from "element-plus";

const authStore = useAuthStore();

// 控制模态框显示状态
const showModal = ref(false);

// 打开模态框
const openModal = () => {
  showModal.value = true;
};

// 关闭模态框
const closeModal = () => {
  showModal.value = false;
};

// 点击模态框外部关闭
const handleModalClick = (event) => {
  if (event.target.id === "changePasswordModal") {
    closeModal();
  }
};

// 键盘事件监听 - 按ESC关闭模态框
const handleKeyDown = (event) => {
  if (event.key === "Escape" && showModal.value) {
    closeModal();
  }
};

const { id: userId, username } = authStore.user;
const posts = ref([]);
const topics = ref([]);
const postsNum = ref(0);

onBeforeMount(async () => {
  const { data: postsData } = await getUserPostsService(userId);
  const { data: topicsData } = await getUserTopicsService(userId);

  posts.value = postsData;
  topics.value = topicsData;

  postsNum.value = postsData.length + topicsData.length;
});

// 删除策略
const deleteStrategies = {
  post: (params) =>
    deleteUserPostService({
      post_id: params.post_id,
      user_id: params.user_id,
    }),
  topic: (params) =>
    deleteUserTopicService({
      topic_id: params.topic_id,
      user_id: params.user_id,
    }),
};

const deleteContent = async ({ post_id, topic_id, user_id, apiType }) => {
  if (apiType === "post" && !post_id) throw new Error("帖子ID不能为空");
  if (apiType === "topic" && !topic_id) throw new Error("话题ID不能为空");

  const strategy = deleteStrategies[apiType];
  if (!strategy) throw new Error("无效的删除类型");

  return strategy({
    post_id: apiType === "post" ? post_id : undefined,
    topic_id: apiType === "topic" ? topic_id : undefined,
    user_id,
  });
};

// 删除攻略贴
const deletePost = async (postId) => {
  try {
    await deleteContent({
      post_id: postId,
      user_id: userId,
      apiType: "post",
    });
    // 删除成功后从列表中移除
    posts.value = posts.value.filter((post) => post.id !== postId);
    postsNum.value--;
    ElMessage.success("删除成功");
  } catch (error) {
    ElMessage.error("删除失败");
    console.error("删除失败:", error);
  }
};

// 删除讨论贴
const deleteTopic = async (topicId) => {
  try {
    await deleteContent({
      topic_id: topicId,
      user_id: userId,
      apiType: "topic",
    });
    // 删除成功后从列表中移除
    topics.value = topics.value.filter((topic) => topic.id !== topicId);
    postsNum.value--;
    ElMessage.success("删除成功");
  } catch (error) {
    console.error("删除失败:", error);
  }
};
</script>

<template>
  <!-- 主要内容 -->
  <div class="container main-content">
    <div class="content-grid">
      <!-- 左侧个人信息 -->
      <div>
        <!-- 个人信息卡片 -->
        <div class="profile-card">
          <div class="profile-content">
            <div class="profile-header">
              <img
                class="profile-avatar"
                src="https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=500&auto=format&fit=crop&q=60"
                alt="用户头像"
              />
              <div class="profile-info">
                <h2 class="profile-name">
                  {{ username }}
                </h2>
                <p class="profile-date">加入时间：2024-01-01</p>
              </div>
            </div>
            <div class="profile-stats">
              <div class="stat-item">
                <p class="stat-value">{{ postsNum }}</p>
                <p class="stat-label">发帖</p>
              </div>
              <div class="stat-item">
                <p class="stat-value">256</p>
                <p class="stat-label">收藏</p>
              </div>
              <div class="stat-item">
                <p class="stat-value">512</p>
                <p class="stat-label">获赞</p>
              </div>
            </div>
            <div class="profile-actions">
              <!-- <button class="btn-primary">编辑资料</button> -->
              <!-- 发布新话题 -->
              <router-link to="/community/post" class="post-btn">
                <svg
                  fill="none"
                  stroke="currentColor"
                  viewBox="0 0 24 24"
                  width="20"
                  height="20"
                >
                  <path
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 4v16m8-8H4"
                  />
                </svg>
                发布新话题
              </router-link>
              <!-- 修改密码按钮 -->
              <button @click="openModal" class="btn-secondary">修改密码</button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧内容区 -->
      <div>
        <!-- 内容导航 -->
        <div class="content-nav">
          <div class="nav-tabs">
            <a href="#" class="nav-tab active">我的发布</a>
            <a href="#" class="nav-tab">我的收藏</a>
            <a href="#" class="nav-tab">我的评论</a>
            <a href="#" class="nav-tab">我的点赞</a>
          </div>
        </div>

        <!-- 发布列表 -->
        <div class="post-list">
          <!-- 攻略贴 -->
          <div class="post-card" v-for="(item, index) in posts" :key="item.id">
            <div class="post-content">
              <div class="post-header">
                <div class="post-meta">
                  <span class="post-tag tag-guide">攻略</span>
                  <span class="post-date">{{ item.created_at }}</span>
                </div>
                <div class="post-stats">
                  <span class="post-stat">{{ item.view_count }} 浏览</span>
                  <span class="post-stat">32 评论</span>
                  <span class="post-stat">16 点赞</span>
                </div>
              </div>
              <router-link :to="`/guides/article/${item.id}`" class="post-title">
                {{ item.title }}
              </router-link>
              <p class="post-excerpt">{{ item.content }}</p>
              <div class="post-actions">
                <button class="post-action">编辑</button>
                <button @click="deletePost(item.id)" class="post-action delete">
                  删除
                </button>
              </div>
            </div>
          </div>

          <!-- 讨论贴 -->
          <div class="post-card" v-for="(item, index) in topics" :key="item.id">
            <div class="post-content">
              <div class="post-header">
                <div class="post-meta">
                  <span class="post-tag tag-discussion">讨论</span>
                  <span class="post-date">{{ item.created_at }}</span>
                </div>
                <div class="post-stats">
                  <span class="post-stat">{{ item.view_count }} 浏览</span>
                  <span class="post-stat">{{ item.reply_count }} 评论</span>
                  <span class="post-stat">{{ item.like_count }} 点赞</span>
                </div>
              </div>
              <router-link :to="`/community/article/${item.id}`" class="post-title">
                {{ item.title }}
              </router-link>
              <p class="post-excerpt">{{ item.content }}</p>
              <div class="post-actions">
                <button class="post-action">编辑</button>
                <button @click="deleteTopic(item.topic_id)" class="post-action delete">
                  删除{{ item.topic_id }}
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination">
          <ul class="pagination-list">
            <li class="pagination-item">
              <a href="#" class="pagination-link">
                <span>上一页</span>
              </a>
            </li>
            <li class="pagination-item">
              <a href="#" class="pagination-link">1</a>
            </li>
            <li class="pagination-item">
              <a href="#" class="pagination-link active">2</a>
            </li>
            <li class="pagination-item">
              <a href="#" class="pagination-link">3</a>
            </li>
            <li class="pagination-item">
              <a href="#" class="pagination-link">
                <span>下一页</span>
              </a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>

  <!-- 修改密码模态框 -->
  <div
    id="changePasswordModal"
    class="modal"
    :class="{ show: showModal }"
    @click="handleModalClick"
    @keydown="handleKeyDown"
    aria-labelledby="modal-title"
    role="dialog"
    aria-modal="true"
  >
    <div class="modal-content">
      <div class="modal-header">
        <h3 class="modal-title">修改密码</h3>
        <button type="button" class="modal-close" aria-label="关闭" @click="closeModal">
          <svg
            width="24"
            height="24"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
          >
            <path
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="2"
              d="M6 18L18 6M6 6l12 12"
            />
          </svg>
        </button>
      </div>
      <div class="modal-body">
        <form id="passwordForm">
          <div class="form-group">
            <label class="form-label">当前密码</label>
            <input
              type="password"
              class="form-input"
              placeholder="请输入当前密码"
              required
            />
          </div>
          <div class="form-group">
            <label class="form-label">新密码</label>
            <input
              type="password"
              class="form-input"
              placeholder="请输入新密码"
              required
            />
            <div class="form-error">密码长度至少8位，包含字母和数字</div>
          </div>
          <div class="form-group">
            <label class="form-label">确认新密码</label>
            <input
              type="password"
              class="form-input"
              placeholder="请再次输入新密码"
              required
            />
            <div class="form-error">两次输入的密码不一致</div>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
        <button type="submit" form="passwordForm" class="btn btn-primary">
          确认修改
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
body {
  font-family: "Noto Sans SC", sans-serif;
  background-color: #f9fafb;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1280px;
  margin: 0 auto;
  padding: 0 1rem;
}

/* 导航栏样式 */
.navbar {
  background-color: white;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.navbar-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 4rem;
  padding: 0 1rem;
}

.navbar-brand {
  display: flex;
  align-items: center;
}

.navbar-logo {
  height: 2rem;
  width: auto;
}

.navbar-title {
  margin-left: 0.5rem;
  font-size: 1.25rem;
  font-weight: bold;
  color: #059669;
}

.navbar-nav {
  display: none;
}

.nav-link {
  color: #6b7280;
  text-decoration: none;
  padding: 0.5rem 1rem;
  font-size: 0.875rem;
  font-weight: 500;
  border-bottom: 2px solid transparent;
}

.nav-link:hover {
  color: #374151;
  border-bottom-color: #d1d5db;
}

.nav-link.active {
  color: #111827;
  border-bottom-color: #059669;
}

.login-btn {
  background-color: #059669;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 500;
  border: none;
  cursor: pointer;
}

.login-btn:hover {
  background-color: #047857;
}

/* 主要内容区域 */
.main-content {
  padding: 2rem 0;
}

.content-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 2rem;
}

/* 个人信息卡片 */
.profile-card {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.profile-content {
  padding: 1.5rem;
}

.profile-header {
  display: flex;
  align-items: center;
}

.profile-avatar {
  width: 5rem;
  height: 5rem;
  border-radius: 9999px;
}

.profile-info {
  margin-left: 1rem;
}

.profile-name {
  font-size: 1.25rem;
  font-weight: bold;
  color: #111827;
  margin: 0;
}

.profile-date {
  font-size: 0.875rem;
  color: #6b7280;
  margin-top: 0.25rem;
}

.profile-stats {
  display: flex;
  justify-content: space-between;
  margin-top: 1.5rem;
  padding-top: 1.5rem;
  border-top: 1px solid #e5e7eb;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 1.5rem;
  font-weight: 600;
  color: #111827;
  margin: 0;
}

.stat-label {
  font-size: 0.875rem;
  color: #6b7280;
  margin-top: 0.25rem;
}

.profile-actions {
  margin-top: 1rem;
}

.btn-primary {
  width: 100%;
  background-color: #059669;
  color: white;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 500;
  border: none;
  cursor: pointer;
}

.btn-primary:hover {
  background-color: #047857;
}

.btn-secondary {
  width: 100%;
  background-color: white;
  color: #059669;
  padding: 0.5rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 500;
  border: 1px solid #059669;
  cursor: pointer;
  margin-top: 0.5rem;
}

.btn-secondary:hover {
  background-color: #f0fdf4;
}

/* 个人设置 */
.settings-card {
  margin-top: 2rem;
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.settings-content {
  padding: 1.5rem;
}

.settings-title {
  font-size: 1.125rem;
  font-weight: 500;
  color: #111827;
  margin-bottom: 1rem;
}

.settings-list {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.settings-link {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #6b7280;
  text-decoration: none;
  font-size: 0.875rem;
}

.settings-link:hover {
  color: #111827;
}

/* 内容导航 */
.content-nav {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  margin-bottom: 2rem;
}

.nav-tabs {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
}

.nav-tab {
  padding: 1rem 1.5rem;
  font-size: 0.875rem;
  font-weight: 500;
  color: #6b7280;
  text-decoration: none;
  border-bottom: 2px solid transparent;
  white-space: nowrap;
}

.nav-tab:hover {
  color: #374151;
  border-bottom-color: #d1d5db;
}

.nav-tab.active {
  color: #059669;
  border-bottom-color: #059669;
}

/* 发布列表 */
.post-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.post-card {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.post-content {
  padding: 1.5rem;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-meta {
  display: flex;
  align-items: center;
}

.post-tag {
  display: inline-flex;
  align-items: center;
  padding: 0.25rem 0.625rem;
  border-radius: 9999px;
  font-size: 0.75rem;
  font-weight: 500;
}

.tag-guide {
  background-color: #dcfce7;
  color: #166534;
}

.tag-discussion {
  background-color: #dbeafe;
  color: #1e40af;
}

.post-date {
  margin-left: 0.5rem;
  font-size: 0.875rem;
  color: #6b7280;
}

.post-stats {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.post-stat {
  font-size: 0.875rem;
  color: #6b7280;
}

.post-title {
  margin-top: 0.5rem;
  font-size: 1.125rem;
  font-weight: 500;
  color: #111827;
  text-decoration: none;
}

.post-excerpt {
  margin-top: 0.5rem;
  font-size: 0.875rem;
  color: #6b7280;
}

.post-actions {
  margin-top: 1rem;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.post-action {
  font-size: 0.875rem;
  color: #6b7280;
  text-decoration: none;
  cursor: pointer;
}

.post-action:hover {
  color: #374151;
}

.post-action.delete {
  color: #ef4444;
}

.post-action.delete:hover {
  color: #dc2626;
}

/* 分页 */
.pagination {
  margin-top: 2rem;
  display: flex;
  justify-content: center;
}

.pagination-list {
  display: flex;
  list-style: none;
  padding: 0;
  margin: 0;
}

.pagination-item {
  margin: 0 -1px;
}

.pagination-link {
  display: inline-flex;
  align-items: center;
  padding: 0.5rem 1rem;
  border: 1px solid #d1d5db;
  background-color: white;
  color: #6b7280;
  font-size: 0.875rem;
  font-weight: 500;
  text-decoration: none;
}

.pagination-link:hover {
  background-color: #f9fafb;
}

.pagination-link.active {
  background-color: #ecfdf5;
  color: #059669;
}

/* 模态框 */
.modal {
  position: fixed;
  inset: 0;
  background-color: rgba(107, 114, 128, 0.75);
  display: none;
  z-index: 50;
  overflow-y: auto;
  padding: 1rem;
}

.modal-content {
  position: relative;
  background-color: white;
  border-radius: 0.75rem;
  margin: 2rem auto;
  max-width: 32rem;
  width: 100%;
  overflow: hidden;
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  transform: translateY(0);
  transition: transform 0.3s ease-out;
}

.modal-header {
  padding: 1.5rem;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: #111827;
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  padding: 0.5rem;
  cursor: pointer;
  color: #6b7280;
  transition: color 0.2s;
}

.modal-close:hover {
  color: #111827;
}

.modal-body {
  padding: 1.5rem;
}

.modal-footer {
  padding: 1.5rem;
  border-top: 1px solid #e5e7eb;
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

/* 表单样式 */
.form-group {
  margin-bottom: 1.25rem;
}

.form-label {
  display: block;
  font-size: 0.875rem;
  font-weight: 500;
  color: #374151;
  margin-bottom: 0.5rem;
}

.form-input {
  width: 100%;
  padding: 0.625rem 0.75rem;
  box-sizing: border-box;
  border: 1px solid #d1d5db;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  color: #111827;
  transition: all 0.2s;
}

.form-input:focus {
  outline: none;
  border-color: #059669;
  box-shadow: 0 0 0 3px rgba(5, 150, 105, 0.1);
}

.form-input.error {
  border-color: #dc2626;
}

.form-error {
  color: #dc2626;
  font-size: 0.75rem;
  margin-top: 0.375rem;
  display: none;
}

.form-error.show {
  display: block;
}

.btn {
  padding: 0.625rem 1rem;
  border-radius: 0.5rem;
  font-size: 0.875rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #059669;
  color: white;
  border: none;
}

.btn-primary:hover {
  background-color: #047857;
}

.btn-secondary {
  background-color: white;
  color: #374151;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover {
  background-color: #f9fafb;
}

/* 动画效果 */
@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal.show {
  display: block;
  animation: modalFadeIn 0.3s ease-out;
}

/* 响应式设计 */
@media (min-width: 640px) {
  .navbar-nav {
    display: flex;
    gap: 2rem;
  }
}

@media (min-width: 1024px) {
  .content-grid {
    grid-template-columns: 1fr 2fr;
  }
}

.post-btn {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0.5rem 1rem;
  box-sizing: border-box;
  text-decoration: none;
  border: none;
  border-radius: 0.375rem;
  background-color: #059669;
  color: white;
  font-size: 0.875rem;
  font-weight: 500;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: background 0.2s;
}
.post-btn:hover {
  background-color: #047857;
}
.post-btn svg {
  margin-right: 0.5rem;
}

/* 页脚样式 */
.footer {
  background-color: white;
  margin-top: 3rem;
  padding: 3rem 0;
}

.footer-nav {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 1.25rem;
}

.footer-link {
  color: #6b7280;
  text-decoration: none;
  font-size: 1rem;
  padding: 0.5rem;
}

.footer-link:hover {
  color: #374151;
}

.footer-copyright {
  margin-top: 2rem;
  text-align: center;
  color: #9ca3af;
  font-size: 1rem;
}
</style>
